import 'package:flutter/material.dart';

enum TapType { pressed, longpress }

class TapTransitionWidget extends StatefulWidget {
  late Widget child;
  late bool isTransition;
  late Duration delay;
  late Function()? onPressed;
  late Function()? onLongPress;
  late Color? color;

  TapTransitionWidget(
      {Key? key,
      required this.child,
      this.isTransition = true,
      this.onPressed,
      this.onLongPress,
      this.delay = const Duration(milliseconds: 150),
      this.color})
      : super(key: key);

  _TapTransitionWidgetState createState() => _TapTransitionWidgetState();
}

class _TapTransitionWidgetState extends State<TapTransitionWidget>
    with TickerProviderStateMixin {
  TapType _type = TapType.pressed;
  late AnimationController _aniController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _aniController = AnimationController(
      vsync: this,
      duration: widget.delay,
    )..addListener(() {
        if (_aniController.value == 1 && _type == TapType.pressed) {
          _aniController.reverse();
        }
      });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _aniController.stop();
    _aniController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        FocusManager.instance.primaryFocus?.unfocus();
        _type = TapType.pressed;
        if (widget.isTransition) _aniController.forward();
        widget.onPressed?.call();
      },
      onLongPress: () {
        FocusManager.instance.primaryFocus?.unfocus();
        _type = TapType.longpress;
        if (widget.isTransition) _aniController.forward();
        widget.onLongPress?.call();
      },
      onLongPressUp: () {
        if (widget.isTransition) _aniController.reverse();
      },
      child: AnimatedBuilder(
        animation: _aniController,
        builder: (context, child) {
          return Transform.scale(
              scale: 1 - (_aniController.value * 0.05), // 由1到0.95过渡
              child: Container(
                child: widget.child,
                // color: widget.color??Colors.transparent.withOpacity(0 + (_aniController.value * 0.2)),
              ));
        },
      ),
    );
  }
}
